package cn.net.pojo;

import cn.net.httpclient.HttpClientSystem;
import cn.net.model.*;
import cn.net.netmodel.RequestParams;
import cn.net.util.ParamsUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.message.BasicNameValuePair;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.util.*;

/**
 * Created by Administrator on 2017/8/23.
 */
@Component
public class TT {

    private static final Log log = LogFactory.getLog(TT.class);

    @Autowired
    private HttpClientSystem client;

    public static void main(String[] args) {
        HttpClientSystem client = new HttpClientSystem();
        CacheDataObject res = new TT().TTSearch(client, "ADL", "SYD", "2018-12-29", "4");

        System.out.println(res.getReturnObject().getRoutings().get(0).getAdultPrice());
    }

    public CacheDataObject TTSearch(RequestParams params) {
        CacheDataObject cdo = TTSearch(client, params.getDep(), params.getArr(), params.getTime(), params.getCount());
        return cdo;
    }

    public CacheDataObject TTSearch(HttpClientSystem client, String dep, String arr, String time, String count) {

        DateTime dateTime = DateTime.parse(time, DateTimeFormat.forPattern("yyyy-MM-dd"));

        time = dateTime.toString("dd MMM yyyy", Locale.ENGLISH);

        String token = getTocken(client);

        HttpPost post = new HttpPost("https://booking.tigerair.com.au/TigerAirIBE/Booking/Search");
        post.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;" +
                "q=0.8");
        post.addHeader("Cache-Control", "max-age=0");
        post.addHeader("Connection", "keep-alive");
        post.addHeader("Content-Type", "application/x-www-form-urlencoded");
        post.addHeader("Host", "booking.tigerair.com.au");
        post.addHeader("DNT", "1");
        post.addHeader("Origin", "https://booking.tigerair.com.au");
        post.addHeader("Pragma", "no-cache");
        post.addHeader("Referer", "https://booking.tigerair.com.au/TigerAirIBE/Booking/Search");
        post.addHeader("Upgrade-Insecure-Requests", "1");
        post.addHeader("User-Agent", ParamsUtil.USER_AGENT_CHROME);

        LinkedList<NameValuePair> params = new LinkedList<>();

        params.add(new BasicNameValuePair("__RequestVerificationToken", token));
        params.add(new BasicNameValuePair("TripKind", "oneWay"));
        params.add(new BasicNameValuePair("onoffswitch", "on"));
        params.add(new BasicNameValuePair("Origin", dep));
        params.add(new BasicNameValuePair("Destination", arr));
        params.add(new BasicNameValuePair("DepartureDate", time));
        params.add(new BasicNameValuePair("ReturnDate", time));
        params.add(new BasicNameValuePair("AdultCount", count));
        params.add(new BasicNameValuePair("ChildCount", "0"));
        params.add(new BasicNameValuePair("InfantCount", "0"));
        params.add(new BasicNameValuePair("PromoCode", ""));
        params.add(new BasicNameValuePair("SelectedCurrencyCode", "AUD"));

        post.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));

        CloseableHttpResponse response;
        log.info("TT action======req");
        for (Cookie c : client.cookieStore().getCookies()) {
            System.out.println(c.getName() + ":" + c.getValue());
        }
        response = client.post( post);
        log.info("TT action======res:" + response);
        if (response == null)
            return null;
        if (response.getStatusLine().getStatusCode() != 302)
            return null;
        Header[] headers = response.getHeaders("Location");
        String url = headers[0].getValue();
        System.out.println(url);
        if (!url.contains("Select"))
            return null;
        url = "https://booking.tigerair.com.au" + url;

//        Header[] headers2 = response.getHeaders("Set-Cookie");
//        String cookie = "";
//        for (Header h : headers2) {
//            cookie += h.getValue();
//            cookie += " ; ";
//        }

        HttpGet get = new HttpGet(URI.create(url));

        get.addHeader("Host", "booking.tigerair.com.au");
        get.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        get.addHeader("Referer", "https://booking.tigerair.com.au/TigerAirIBE/Booking/search");
        get.addHeader("Accept-Language", "zh-CN,zh;q=0.8");
        get.addHeader("Accept-Encoding", "gzip, deflate, sdch, br");
        get.addHeader("DNT", "1");
        String html;
        log.info("TT action======req2");
        html = client.get(get);
        log.info("TT action======res2");
        if (html == null)
            return null;
        CacheDataObject cdo = this.getTTPackage(html, dep, arr, count, dateTime.toString("yyyy-MM-dd"));
        return cdo;
    }

    public String getTocken(HttpClientSystem client) {
        HttpGet get = new HttpGet(URI.create("https://booking.tigerair.com.au/TigerAirIBE/Booking/Search"));
        String s = client.get(get);
        Document doc = Jsoup.parse(s);
        Element element = doc.select("input[name=__RequestVerificationToken]").get(0);
        return element.attr("value");
    }

    private CacheDataObject getTTPackage(String html, String dep, String arr, String count, String time) {
        String departureDate = "";// 出发日期
        String departureTime = "";// 出发时间
        String arriveDate = "";// 到达时间
        String arriveTime = "";// 到达时间
        String lightPrice = "";// 经济票价
        String currency = "AUD"; // 币种 String
        String flight = "";// 航班号
        String carrier = "";// 航司代码
        String guid = "", guidTmp = "";
        String depAirport = dep, arrAirport = arr;

        Document document = Jsoup.parse(html);

//        carrier = document.select("span[class=lowest-day-fare]").get(1).text().substring(0, 3);

        Element element = document.getElementById("table-0");
        Elements elements = element.children().get(0).children();

        List<Routing> routings = new ArrayList();

        for (Element e : elements) {
            carrier = "";
            flight = "";
            if (!e.children().get(0).children().toString().equals("")) {

                String attr = e.attr("class");
                if (!attr.equals(""))
                    continue;


                if (e.child(0).text().contains("no flights")) {
                    continue;//当天没有航班
                }

                String text = e.child(0).child(1).text();
                String[] strings = text.split(" ");
                carrier = strings[0];
                flight = strings[1];
                Elements select = e.select("td[class=js-fare-selection flight-price]");
                if (select.size() == 0)
                    continue;
                Element times = e.select("td[class=js-fare-selection flight-price]").get(0);
                String deptime = times.attr("data-dep-date").replace("T", " ");
                String arrtime = times.attr("data-arr-date").replace("T", " ");
                lightPrice = e.child(2).text().split(" ")[1];

                List<Segment> fromSegments = new ArrayList();

                Segment segment = new Segment();
                segment.setFlightNumber(carrier + flight);
                segment.setCarrier(carrier);
                segment.setDepAirport(depAirport);
                segment.setDepTime(DateTime.parse(deptime, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm"))
                        .toString("yyyyMMddHHmm"));
                segment.setArrAirport(arrAirport);
                segment.setArrTime(DateTime.parse(arrtime, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm"))
                        .toString("yyyyMMddHHmm"));
                segment.setCodeShare(false);
                segment.setStopCities("");// 空
                segment.setCabin("Y");// Y仓位
                segment.setAircraftCode("");// 机型
                segment.setCabinClass(1);
                fromSegments.add(segment);

                Rule rl = new Rule();
                rl.setHasRefund(0);
                rl.setRefund("一旦出票，不允许退票，包括已经代为收取的机场建设费、燃油附加费和相关税费也不可退");
                rl.setPartRefund(0);
                rl.setPartRefundPrice(0);
                rl.setHasEndorse(0);
                rl.setEndorse("请咨询旺旺客服");
                rl.setPartEndorse(0);
                rl.setPartEndorsePrice(0);
                rl.setEndorsement(0);
                rl.setHasBaggage(0);
                rl.setBaggage("廉价航空公司无免费托运行李额，添加托运行李额请联系旺旺客服");
                rl.setHasNoShow(0);
                rl.setNoShowLimitTime(0);
                rl.setPenalty(0);
                rl.setSpecialNoShow(3);
                rl.setOther("");

                Routing routing = new Routing();
                routing.setAdultPrice(Double.parseDouble(lightPrice));
                routing.setAdultTax(0);// 没有抓所以0
                routing.setAdultTaxType(0);
                routing.setApplyType(0);
                routing.setChildPrice(routing.getAdultPrice());
                routing.setChildTax(routing.getAdultTax());
                routing.setChildTaxType(routing.getAdultTaxType());
                routing.setData("TT_" + UUID.randomUUID().toString());
                routing.setCurrency(currency);
                routing.setFromSegments(fromSegments);
                routing.setNationality("");
                routing.setNationalityType(0);
                routing.setPriceType(0);// 票价类型 成人 1
                routing.setRetSegments(new ArrayList<Segment>());
                routing.setRule(rl);
                routing.setSuitAge("");
                routing.setTicketInvoiceType(0);
                routings.add(routing);

            }
        }

        ReturnObject ro = new ReturnObject();
        ro.setRoutings(routings);
        ro.setStatus(0);
        ro.setMsg("true");
        CacheDataObject cdo = new CacheDataObject();
        cdo.setDbFlag(0);
        cdo.setFlag("true");
        cdo.setReturnObject(ro);
        cdo.setTimeNow(DateTime.now().toString());
        return cdo;
    }
}
